package com.mvvm.ktnet.http.rxhttpparser


/**
 *
 * @ProjectName:    Kotlin_Mvvm
 * @Package:        com.android.alex.http.response
 * @ClassName:      ResponseParser
 * @Description:     java类作用描述
 * @Author:         Alex
 * @CreateDate:     2020/7/27 18:18
 * @UpdateUser:     更新者：
 * @UpdateDate:     2020/7/27 18:18
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */

import com.alibaba.fastjson.JSON
import com.mvvm.ktnet.http.BaseEntity
import com.mvvm.ktnet.http.base.IBaseResponse

import rxhttp.wrapper.annotation.Parser
import rxhttp.wrapper.entity.ParameterizedTypeImpl
import rxhttp.wrapper.parse.AbstractParser
import rxhttp.wrapper.utils.convert
import java.io.IOException
import java.lang.reflect.Type

@Parser(name = "ResponseData", wrappers = [MutableList::class])
open class ResponseDataParser<T> : AbstractParser<T> {

    protected constructor() : super()

    constructor(type: Type) : super(type)

    @Throws(IOException::class)
    override fun onParse(response: okhttp3.Response): T {
        val type: Type = ParameterizedTypeImpl[BaseEntity::class.java, mType]
        val data: BaseEntity<T> = response.convert(type)
        var t = data.data() //获取data字段
        if (t == null && mType === String::class.java) {
            @Suppress("UNCHECKED_CAST")
            t = data.msg() as T
        }
        if (data.code() != 1 || t == null) {
            if (data.code() ==9) {


            }
            throw CustomParseException(
                data.code().toString(),
                data.msg(),
                response,
                JSON.toJSONString(data)
            )
        }
        return t
    }
}
